<?php
class Ware {
	public static function getbyid($id){
		return Db::get('_Ware')->select()->where(array('id'=>$id))->getOne();
	}
	
	/**
	 * 取当前的材料库存价值
	 * @return Array[price,amount,total]
	 */
	public static function getValues($ware_id){
		return Db::get(__CLASS__)->select('amount,price,amount*price AS total')->where(array('id'=>$ware_id))->getOne();
	}
	
	/**
	 * 更新材料库存价值；方法内做出库数量检查
	 * @param Array [price,amount,ware_id]
	 * @param int   $rotate 1为入库, -1为出库
	 * @return bool
	 */
	public static function renewValues($ware, $rotate=1, &$errmsg=''){
		$rotate  = ($rotate>0?1:-1);
		$ware_id = $ware['ware_id'];
		
		$data = self::getValues($ware_id);
		if(!$data){
			$errmsg = '无此材料';
			return false;
		}
		if($ware['amount']==0){
			$errmsg = '材料数量不能为空';
			return false;
		}
		if($rotate<0 && $data['amount']<$ware['amount']){
			$errmsg = '库存数量小于要出库数量';
			return false;
		}
		//todo: 这种回写数量方式存在隐患，应让mysql做减法，并取回结果验证正负；
		//		但事务是在外部打开和关闭的，在此方法内不能做事务。
		$data['amount'] += ( $rotate * $ware['amount'] );
		$data['total']  += ( $rotate * $ware['amount'] * $ware['price'] );
		$data['price']   = ($data['amount']>0) ? $data['total'] / $data['amount'] : 0;
		Db::get(__CLASS__)->update($data)->where(array('id'=>$ware_id))->exec();
		if(!Db::get(__CLASS__)->affectedRows()){
			$errmsg = '修改结存信息失败';
			return false;
		}
		return true;
	}
	
	public static function getList($where='',$s=0,$l=0){
		return Db::get('_Ware')->select()->where($where)->limit($s,$l)->order('sno ASC')->hkey('id')->getAll();
	}
	
	public static function count($where=''){
		return Db::get(__CLASS__)->count()->where($where)->getCol();
	}
	
}
?>
